import {Component, OnDestroy, OnInit} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, FormArray} from '@angular/forms';
import {CommonService} from './../../../shared/service/common.service';
import { forbiddenNameValidator } from './../../../shared/directive/forbidden-name.directive';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-form-control',
  templateUrl: './form-control.component.html',
  styleUrls: ['./form-control.component.scss']
})
export class FormControlComponent implements OnInit, OnDestroy {

  formControlInst: object = this.commonService.formControlInst;
  formTree: object = this.commonService.formTree;
  attrOutput: string = '';
  methodOutput: string = '';

  // 保存valueChanges和statusChanges事件，用于销毁
  valueChangesList = [];
  statusChangesList = [];

  enableValue = '';
  disableValue = '';
  parentNodeName = '';
  isModalVisible = false;     // 控制弹出框是否显示
  formControlSubscription = new Subscription();
  formTreeSubscription = new Subscription();
  formNodeSubscription = new Subscription();

  constructor(
    private fb: FormBuilder,
    private commonService: CommonService
  ) {
    this.listenEvents();
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.formControlSubscription.unsubscribe();
    this.formTreeSubscription.unsubscribe();
    this.valueChangesList.forEach(valueChange => {
      valueChange.unsubscribe();
    });
    this.statusChangesList.forEach(statusChange => {
      statusChange.unsubscribe();
    });
  }

  /**
   * 获取控件的value值
   */
  getValue() {
    console.log(this.formControlInst);
    this.attrOutput = this.formControlInst['name'] + '控件的value值为： ' + this.commonService.convertType(this.formControlInst['instantiation'].value);
  }

  /**
   * 获取控件的valid值
   */
  getValid() {
    this.attrOutput = this.formControlInst['name'] + '的valid值为：' + this.commonService.convertType(this.formControlInst['instantiation'].valid);
  }

  /**
   * 获取控件的invalid值
   */
  getInValid() {
    this.attrOutput = this.formControlInst['name'] + '的invalid值为：' + this.commonService.convertType(this.formControlInst['instantiation'].invalid);
  }

  /**
   * 获取控件的disabled值
   */
  getDisabled() {
    this.attrOutput = this.formControlInst['name'] + '的disabled值为：' + this.commonService.convertType(this.formControlInst['instantiation'].disabled);
  }

  /**
   * 获取控件的enabled值
   */
  getEnabled() {
    this.attrOutput = this.formControlInst['name'] + '的enabled值为：' + this.commonService.convertType(this.formControlInst['instantiation'].enabled);
  }

  /**
   * 获取控件的pristine值
   */
  getPristine() {
    this.attrOutput = this.formControlInst['name'] + '的pristine值为：' + this.commonService.convertType(this.formControlInst['instantiation'].pristine);
  }

  /**
   * 获取控件的dirty值
   */
  getDirty() {
    this.attrOutput = this.formControlInst['name'] + '的dirty值为：' + this.commonService.convertType(this.formControlInst['instantiation'].dirty);
  }

  /**
   * 获取控件的untouched值
   */
  getUntouched() {
    this.attrOutput = this.formControlInst['name'] + '的untouched值为：' + this.commonService.convertType(this.formControlInst['instantiation'].untouched);
  }

  /**
   * 获取控件的touched值
   */
  getTouched() {
    this.attrOutput = this.formControlInst['name'] + '的touched值为：' + this.commonService.convertType(this.formControlInst['instantiation'].touched);
  }

  /**
   * 获取父控件
   */
  getParentControl() {
    this.attrOutput = '请打开控制台查看输出信息';
    console.log(this.formControlInst['name'] + '的父控件是： ');
    console.log(this.formControlInst['instantiation'].parent);
  }

  /**
   * 获取根控件
   */
  getRootControl() {
    this.attrOutput = '请打开控制台查看输出信息';
    console.log(this.formControlInst['name'] + '的根控件是： ');
    console.log(this.formControlInst['instantiation'].root);
  }

  /**
   * 获取同步校验器validator值
   */
  getValidator() {
    this.attrOutput = this.formControlInst['name'] + '的同步校验器函数为： \n' + this.commonService.convertType(this.formControlInst['instantiation'].validator);
  }

  /**
   * 获取并监听控件的valueChanges值
   */
  getValueChanges() {
    const parentName = this.commonService.relationShip.find(node => node['name'] === this.formControlInst['name'])['parent'];

    // 如果valueChanges列表中没有对这个input框进行绑定，那才对它进行绑定，避免重复
    if (!this.valueChangesList.find(item => item['name'] === this.formControlInst['name'])) {
      const formControlSubscription = this.formControlInst['instantiation'].valueChanges.subscribe((data) => {
        console.log(this.formControlInst['name'] + '的控件值为：' + data);
      });
      this.valueChangesList.push({
        name: this.formControlInst['name'],
        subscription: formControlSubscription
      });
    }

    // 绑定控件的父节点valueChange事件
    if (!this.valueChangesList.find(item => item['name'] === parentName)) {
      const parentSubscription = this.formControlInst['instantiation'].parent.valueChanges.subscribe((data) => {
        console.log(this.formControlInst['name'] + '的父控件' + parentName + '的值为： \n' + this.commonService.convertType(data));
      });
      this.valueChangesList.push({
        name: parentName,
        subscription: parentSubscription
      });
    }

    this.attrOutput = '请打开控制台查看valueChanges的值，它属于Observable类型，现已使用subscribe方法对' + this.formControlInst['name'] + '输入框进行订阅。\n可以通过修改它的值，或者调用它的disable和enable方法来触发这个订阅事件，同样在控制台查看订阅事件的输出。';
    console.log(this.formControlInst['name'] + '的valueChanges值是： ');
    console.log(this.formControlInst['instantiation'].valueChanges);
  }

  /**
   * 获取并监听控件的statusChanges值
   */
  getStatusChanges() {
    const parentName = this.commonService.relationShip.find(node => node['name'] === this.formControlInst['name'])['parent'];

    // 如果valueChanges列表中没有对这个input框进行绑定，那才对它进行绑定，避免重复
    if (!this.statusChangesList.find(item => item['name'] === this.formControlInst['name'])) {
      const formControlSubscription = this.formControlInst['instantiation'].statusChanges.subscribe((data) => {
        console.log(this.formControlInst['name'] + '控件的状态值为：' + data);
      });
      this.statusChangesList.push({
        name: this.formControlInst['name'],
        subscription: formControlSubscription
      });
    }

    // 绑定控件的父节点valueChange事件
    if (!this.statusChangesList.find(item => item['name'] === parentName)) {
      const parentSubscription = this.formControlInst['instantiation'].parent.statusChanges.subscribe((data) => {
        console.log(this.formControlInst['name'] + '的父控件' + parentName + '的状态值为： \n' + this.commonService.convertType(data));
      });
      this.statusChangesList.push({
        name: parentName,
        subscription: parentSubscription
      });
    }

    this.attrOutput = '请打开控制台查看statusChanges的值，它属于Observable类型，现已使用subscribe方法对' + this.formControlInst['name'] + '输入框进行订阅。\n可以通过修改它的值，或者调用它的disable和enable方法来触发这个订阅事件，同样在控制台查看订阅事件的输出。';
    console.log(this.formControlInst['name'] + '的statusChanges值是： ');
    console.log(this.formControlInst['instantiation'].statusChanges);
  }

  /**
   * 获取控件的errors值
   */
  getErrors() {
    this.attrOutput = this.formControlInst['name'] + '的errors值为：' + this.commonService.convertType(this.formControlInst['instantiation'].errors);
  }


  /* 以下是方法列表 */
  /**
   * 设置控件的同步校验器
   */
  setValidators(regExp) {
    this.formControlInst['instantiation'].setValidators(forbiddenNameValidator(eval(regExp)));
    this.methodOutput = '设置成功，请在' + this.formControlInst['name'] + '输入框尝试';
  }

  /**
   * 设置控件的value值
   */
  setValue(value) {
    this.formControlInst['instantiation'].setValue(value);
    this.methodOutput = '设置成功，请在' + this.formControlInst['name'] + '输入框查看value值';
  }

  /**
   * 启用控件
   */
  handleEnableValueChange(enableParam) {
    if (enableParam) {
      this.formControlInst['instantiation'].enable(enableParam);
      this.methodOutput = '已启用' + this.formControlInst['name'] + '控件';
    }
  }

  /**
   * 禁用控件
   */
  handleDisableValueChange(disableParam) {
    if (disableParam) {
      this.formControlInst['instantiation'].disable(disableParam);
      this.methodOutput = '已禁用' + this.formControlInst['name'] + '控件';
    }
  }

  /**
   * 设置父控件
   */
  handleSetParentChange(parentName) {
    this.commonService.getFormNodeInstance('formGroup', parentName, this.commonService.formInst, 'setParentNode');
  }

  /**
   * 清空同步校验器
   */
  clearValidators() {
    this.formControlInst['instantiation'].clearValidators();
    this.methodOutput = '已清空' + this.formControlInst['name'] + '控件的同步校验器';
  }

  /**
   * 把该控件标记为touched
   */
  markAsTouched() {
    this.formControlInst['instantiation'].markAsTouched();
    this.methodOutput = '1、已将' + this.formControlInst['name'] + '控件标记为touched\n' +
      '2、此时它的touched属性值为true，untouched属性值为false\n' +
      '3、该方法相当于在js模拟人为触发过该控件';
  }

  /**
   * 把该控件标记为untouched
   */
  markAsUntouched() {
    this.formControlInst['instantiation'].markAsUntouched();
    this.methodOutput = '1、已将' + this.formControlInst['name'] + '控件标记为untouched\n' +
      '2、此时它的untouched属性值为true，touched属性值为false';
  }

  /**
   * 设置各控件的值
   */
  // patchValue() {
  //   this.isModalVisible =  true;
  // }
  //
  // handleModalOk(): void {
  //   this.isModalVisible = false;
  // }
  //
  // handleModalCancel(): void {
  //   this.isModalVisible = false;
  // }

  /**
   * 监听subscribe事件
   */
  listenEvents() {
    this.formControlSubscription = this.commonService.formControlSubject.subscribe(formControlObj => {
      this.formControlInst = formControlObj;
    });

    this.formTreeSubscription = this.commonService.formTreeSubject.subscribe(tree => {
      this.formTree = tree;
    });

    this.formNodeSubscription = this.commonService.formNodeSubject.subscribe(nodeObj => {
      if (nodeObj['operate'] === 'setParentNode') {
        this.formControlInst['instantiation'].setParent(nodeObj['instance']);
        this.methodOutput = '已将' + this.formControlInst['name'] + '控件的父控件设置为' + nodeObj['name'] + '\n' + '可在控制台查看它的父控件';
      }
    });
  }
}
